package com.stsmobile;

import java.util.ArrayList;

import com.stsmobile.R;
import com.stsmobile.dataclass.Shipment;
import com.stsmobile.dataclass.Specimen;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewSpecimenData extends Activity{

	private String[] specimenTitles;
	private String[][] specimenData;
	private String[][] dataTitles;
	Shipment shipment;
	ArrayList<Specimen> specimenList;
	private BaseExpandableListAdapter listAdapter;

	@Override
	public void onResume(){
		super.onResume();
		if(STSApplication.loggingOut()){
			finish();
		}
		if(STSApplication.toHome()){
			finish();
		}
	}

	@Override
	public void onCreate(Bundle a){
		super.onCreate(a);
		setContentView(R.layout.viewspecimendata);
		shipment = STSApplication.getShipment();
		specimenList = shipment.getSpecimenList();


		Shipment s = STSApplication.getShipment();
		findAndSetText(R.id.shipmentID, " "+s.getShipment_id());
		findAndSetText(R.id.shippedOnText, " "+s.getShipDate());
		findAndSetText(R.id.shipStatusText, " "+s.getShipStatus());
		findAndSetText(R.id.receivedOnText, " "+s.getReceiveDate());
		findAndSetText(R.id.institutionText, " "+s.getInstitution());
		findAndSetText(R.id.labText, " "+s.getLab());

		populateSpecimenTitles();
		populateSpecimenData();

		//Create the expanding specimen list
		ExpandableListView listView = (ExpandableListView) this.findViewById(R.id.expandableListView2);
		listAdapter = new CustomListAdapter(this,specimenTitles,specimenData);
		listView.setAdapter(listAdapter);

		Button back = (Button) this.findViewById(R.id.b_back);
		back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void findAndSetText(int id, String s){
		TextView txt = (TextView) findViewById(id);
		txt.setText(s);
	}
	/**
	 * Initially populates the view's specimen data.
	 * @param id
	 * @param s
	 */
	private void populateSpecimenData()
	{
		specimenData = new String[specimenList.size()][5];
		dataTitles = new String[specimenList.size()][5];
		for (int i = 0; i < specimenList.size(); i++)
		{
			dataTitles[i][0] = specimenList.get(i).getSpecimenTitle()+": ";
			specimenData[i][0] = "" + specimenList.get(i).getSpecimenDescription();
			dataTitles[i][1] = "Specimen Count: ";
			specimenData[i][1] = "" + specimenList.get(i).getQuantity();
			dataTitles[i][2] = "Intact: ";
			specimenData[i][2] = "" + specimenList.get(i).getIntact();
			dataTitles[i][3] = "Damaged: ";
			specimenData[i][3] = "" + specimenList.get(i).getDamaged();
			dataTitles[i][4] = "Missing: ";
			specimenData[i][4] = "" + specimenList.get(i).getMissing();
		}
	}

	/**
	 * initially populates the view's specimen titles
	 * @param id
	 * @param s
	 */
	private void populateSpecimenTitles(){
		specimenTitles = new String[specimenList.size()];
		for (int i = 0; i < specimenList.size(); i++){
			specimenTitles[i] = Integer.toString(specimenList.get(i).getSpecimenID());
		}
	}

	/**
	 * Custom Adapter for the list to use. Gets the data from the shipment
	 * and places it in the list
	 * 
	 * @author Charlie Hatcher
	 */
	public class CustomListAdapter extends BaseExpandableListAdapter{
		private Context context;
		private String[] groups;
		private String[][] children;

		public CustomListAdapter(Context context, String[] groups, String[][] children){
			STSApplication.getShipment();
			this.context = context;
			this.groups=groups;
			this.children=children;
		}

		@Override
		public boolean areAllItemsEnabled()
		{
			return true;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return dataTitles[groupPosition][childPosition]+"\t"+children[groupPosition][childPosition];
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return children[groupPosition].length;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) 
		{
			String child = (String) getChild(groupPosition, childPosition);

			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater.inflate(R.layout.child_row, null);
			}

			TextView childtxt = (TextView) convertView.findViewById(R.id.childname1);

			childtxt.setText(child);

			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return children[groupPosition].length;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return groups[groupPosition];
		}

		@Override
		public int getGroupCount() {
			return groups.length;
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			//			String group = (String) getGroup(groupPosition);

			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater.inflate(R.layout.group_row, null);
			}

			//Group is being generated/updated-- set the title.
			TextView grouptxt = (TextView) convertView.findViewById(R.id.groupname);
			grouptxt.setText("Specimen #"+specimenTitles[groupPosition]);

			return convertView;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return false;
		}

	}


	private static final CharSequence ERROR_CONNECTION = "Unable to connect\n" +
	"to the STS database.";
	private static final CharSequence ERROR_NOT_LOGGED_IN = "User is not logged in.";

	private void makeXmlMessageToast(String result, int duration){
		CharSequence message="";

		//Get error message from server's response.
		int startMessage = result.indexOf("<msg>")+5;
		int endMessage = result.indexOf("</msg>");

		if(startMessage!=-1 && endMessage!=-1)
			message = result.substring(startMessage,endMessage);

		if(message.equals(""))
			message=ERROR_CONNECTION;

		if(message.equals("Sitekey Authentication Failed"))
			message=ERROR_NOT_LOGGED_IN;

		//Display Error Message to User in a Popup
		Context cur_context = getApplicationContext();
		Toast displaymessage = Toast.makeText(cur_context, message, duration);
		displaymessage.show();
	}

	private static final int MENU_LOGOUT = Menu.FIRST;
	private static final int MENU_HOME = Menu.FIRST + 1;

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0,MENU_LOGOUT,0,"Logout");
		menu.add(0,MENU_HOME,0,"Home");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case MENU_LOGOUT:
			logout();
			return true;
		case MENU_HOME:
			home();
			return true;
		}
		return false;
	}

	public void logout(){
		String result = STSApplication.logout();
		makeXmlMessageToast(result, Toast.LENGTH_LONG);
		STSApplication.loggingOut(true);
		finish();
	}

	public void home(){
		STSApplication.toHome(true);
		finish();
	}
}
